<template>
    <div>
      <div class="crumbs">
        <el-breadcrumb separator="/">
          <el-breadcrumb-item
          v-for="(item,index) in breadList"
          :key="index"
          :to="{ path: item.path }"
        >{{item.meta.title}}</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
      <div class="container">
        <div class="handle-box">
          <el-select v-model="query.type" placeholder="景点类型" class="handle-select mr10">
            <el-option key="0" label="自然景点" value="0"></el-option>
            <el-option key="1" label="文化景点" value="1"></el-option>
            <el-option key="2" label="主题公园" value="2"></el-option>
          </el-select>
          <el-input v-model="query.name" placeholder="景点名" class="handle-input mr10"></el-input>
          <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
        </div>
        <el-table :data="tableData" border class="table" ref="multipleTable" header-cell-class-name="table-header">
          <el-table-column prop="id" label="ID" width="55" align="center"></el-table-column>
          <el-table-column prop="name" label="景点名" width="80"></el-table-column>
          <el-table-column prop="type" label="景点类型" width="100" align="center">
            <template #default="scope">
              <el-tag :type="scope.row.type == '0'
                  ? 'Brand Color'
                  : scope.row.type == '1'
                    ? 'success'
                    : 'warning'
                ">
                {{
                  scope.row.type == '0'
                  ? '自然景点'
                  : scope.row.type == '1'
                    ? '文化景点'
                    : '主题公园'
                }}
              </el-tag>
            </template>
          </el-table-column>
          <!-- <el-table-column label="状态" align="center" width="80">
            <template #default="scope">
              <el-tag :type="scope.row.status == '1'
                  ? 'success'
                  : scope.row.status == '0'
                    ? 'danger'
                    : ''
                ">
                {{
                  scope.row.status == '1'
                  ? '正常'
                  : scope.row.status == '0'
                    ? '停用'
                    : '未知'
                }}
              </el-tag>
            </template>
          </el-table-column> -->
          <el-table-column prop="desc" label="简介"></el-table-column>
          <el-table-column prop="address" label="地址"></el-table-column>
          <el-table-column  label="图片">
            <template #default="scope">
              <el-image
              style="width: 100px; height: 100px"
              :src=scope.row.imge
              :fit="fit"></el-image>
            </template>      
          </el-table-column>
          <el-table-column prop="opentime" label="开放时间"></el-table-column>
          <el-table-column prop="createdAt" label="注册时间"></el-table-column>
          <el-table-column label="操作" width="180" align="center">
            <template #default="scope">
              <el-button type="text" icon="el-icon-edit" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
              <el-popconfirm title="确定要删除此景点" confirm-button-text="确定" cancel-button-text="取消"
                @confirm="handleDelete(scope.$index, scope.row)">
                <template #reference>
                  <el-button size="small" type="danger">删除</el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <div class="pagination">
          <el-pagination v-if="totalCount" v-model:currentPage="query.currentPage" v-model:page-size="query.pageSize"
            layout="prev, pager, next, jumper" :total="totalCount" @current-change="handleCurrentChange" />
        </div>
      </div>
      <el-dialog v-model="centerDialogVisible" title="景点编辑" width="40%">
        <div>
          <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="120px" status-icon>
            <el-form-item label="景点名" prop="name">
              <el-input v-model="ruleForm.name" />
            </el-form-item>
            <el-form-item label="景点简介" prop="desc">
              <el-input v-model="ruleForm.desc"/>
            </el-form-item>
            <el-form-item label="开放时间" prop="opentime">
              <el-input v-model="ruleForm.opentime" type="time"/>
            </el-form-item>
            <el-form-item label="图片" prop="img">
              <button @click="updateimg">上传所有图片</button>
              <mavon-editor v-model="ruleForm.img" style="width: 100%;" ref="md" @imgAdd="imgAdd" @imgDel="imgDel" />
            </el-form-item>
            <el-form-item label="景点类型" prop="type">
              <el-radio-group v-model="ruleForm.type">
                <el-radio :label="0">自然景点</el-radio>
                <el-radio :label="1">文化景点</el-radio>
                <el-radio :label="2">主题公园</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="景点地址" prop="address">
              <el-input v-model="ruleForm.address"/>
            </el-form-item>
          </el-form>
        </div>
        <template #footer>
          <span class="dialog-footer">
            <el-button type="primary" @click="submitForm(ruleFormRef)">更新</el-button>
            <el-button @click="resetForm(ruleFormRef)">重置表单</el-button>
            <el-button @click="centerDialogVisible = false">取消</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </template>
  <script>
  import { useRouter, useRoute } from 'vue-router'
  import { ref, reactive, watch } from "vue";
  import request from "../../utils/request";
  import { ElNotification } from "element-plus";
  export default {
    setup() {
      let breadList = [] // 路由集合
      const route = useRoute()
      const router = useRouter();
      const getBreadcrumb=(url)=> {
        let matched = url.matched;
        //如果不是首页
        if ("Home"==matched[0].name) {
          matched[0].meta =  { title: "系统首页" } 
        }
        breadList = matched;
      }
      watch(route, (newValue, oldValue) => {
        // console.log(222222,newValue)
        getBreadcrumb(newValue)
      },{ deep: true, immediate: true });
      
      const resetForm = (formEl) => {
        if (!formEl) return;
        formEl.resetFields();
      };
      const submitForm = async (formEl) => {
        if (!formEl) return;
        await formEl.validate((valid, fields) => {
          if (valid) {
            // console.log("提交更新", fields);
            request
              .request({
                url: "/attraction/update",
                method: "post",
                data: {
                  id: ruleForm.id,
                  name: ruleForm.name,
                  desc: ruleForm.desc,
                  opentime: ruleForm.opentime,
                  address: ruleForm.address,
                  img: ruleForm.img,
                  type: ruleForm.type,
                },
              })
              .then((res) => {
                if (res.data.code == 200) {
                  ElNotification({
                    title: "更新成功",
                    message: "成功更新景点信息",
                  });
                  // 关闭弹窗
                  centerDialogVisible.value = false;
                  //刷新
                getData();
                } else {
                  ElNotification({
                    title: "更新失败",
                    message: "请联系管理员检查失败原因",
                  });
                }
              })
              .catch((e) => {
                ElNotification({
                  title: "更新失败",
                  message: "请联系管理员检查失败原因",
                });
              });
          } else {
            ElNotification({
              title: "校验失败",
              message: "请重新填写信息",
            });
          }
        });
      };
      const ruleForm = reactive({
        id: "",
        name: "",
        desc: "",
        address: "",
        img: "",
        type: 0,
        opentime:"",
      });
      const rules = reactive({
        name: [
          {
            required: true,
            message: "请输入景点名",
            trigger: "blur",
          },
        ],
        desc: [
          {
            required: true,
            message: "简介",
            trigger: "blur",
          },
        ],
        opentime: [
          {
            required: true,
            message: "开放时间",
            trigger: "blur",
          },
        ],
        type: [
          {
            required: true,
            message: "请选择景点类型",
            trigger: "change",
          },
        ],
        address: [
          {
            required: true,
            message: "请输入景点地址",
            trigger: "change",
          },
        ],
        img: [
          {
            required: true,
            message: "请选择景点图片",
            trigger: "blur",
          },
        ],
      });
      const ruleFormRef = ref();
      const centerDialogVisible = ref(false);
      const query = reactive({
        address: "",
        username: "",
        currentPage: 1,
        pageSize: 5,
      });
      const tableData = ref([]);
      const totalCount = ref(0);
      // 获取表格数据
      const getData = () => {
        request
          .request({
            url: "/attraction/getAllAttractionByPage",
            params: {
              type: query.type,
              name: query.name,
              currentPage: query.currentPage,
              pageSize: query.pageSize,
            },
            method: "get",
          })
          .then((res) => {
            //获取当前页的数据
            const rows = res.data.data.rows;
      
      // 遍历修改时间格式
      for (const row of rows) {
        row.createdAt = formatTime(row.createdAt);
        row.imge = row.img.substring(row.img.indexOf("(")+1,row.img.indexOf(")"))
      }

      tableData.value = rows;
      // 获取总记录数
      totalCount.value = res.data.data.count;
    })
    .catch((e) => {
      console.log(e);
    });
};

// 格式化时间函数
const formatTime = (time) => {
  const date = new Date(time);
  const year = date.getFullYear();
  const month = (date.getMonth() + 1).toString().padStart(2, "0");
  const day = date.getDate().toString().padStart(2, "0");
  const hours = date.getHours().toString().padStart(2, "0");
  const minutes = date.getMinutes().toString().padStart(2, "0");
  const seconds = date.getSeconds().toString().padStart(2, "0");

  return `${year}/${month}/${day}/${hours}:${minutes}:${seconds}`;
};
      getData();
      // 查询操作
      const handleSearch = () => {
        getData();
      };
      // 分页导航
      const handleCurrentChange = (val) => {
        query.currentPage = val;
        getData();
        // console.log(val);
      };
      // 删除操作
      const handleDelete = (index, row) => {
        request
          .request({
            url: "/attraction/delete",
            method: "get",
            params: {
              id: row.id,
            },
          })
          .then((res) => {
            if (res.data.msg == "success") {
              getData();
              ElNotification({
                title: "删除成功",
                message: "成功删除景点信息",
              });
            } else {
              ElNotification({
                title: "删除失败",
                message: "请联系管理员检查失败原因",
              });
            }
          })
          .catch((e) => {
            ElNotification({
              title: "删除失败",
              message: "请联系管理员检查失败原因",
            });
          });
      };
      const handleEdit = (index, row) => {
        centerDialogVisible.value = true;
        ruleForm.id = row.id;
        ruleForm.name = row.name;
        ruleForm.desc = row.desc;
        ruleForm.opentime = row.opentime;
        ruleForm.address = row.address;
        ruleForm.img = row.img;
        ruleForm.type = row.type;
      };
      let md = ref(null)
    let img_file = {}
    const imgAdd = (pos, $file) => {
      // 缓存图片信息
      img_file[pos] = $file;
    }
    const imgDel = (pos) => {
      delete img_file[pos];
    }
    const updateimg = ($e) => {
      // 第一步.将图片上传到服务器.
      var formdata = new FormData();
      for (var _img in img_file) {
        formdata.append('files', img_file[_img]);
      }
      request.request({
        url: '/attraction/imageAdd',
        method: 'post',
        data: formdata,
        headers: { 'Content-Type': 'multipart/form-data' },
      }).then((res) => {
        const paths = res.data.data.payload
        /**
         * 例如：返回数据为 res = [[pos, url], [pos, url]...]
         * pos 为原图片标志（0）
         * url 为上传后图片的url地址
         */
        // 第二步.将返回的url替换到文本原位置![...](0) -> ![...](url)
        for(let index=0;index<paths.length;index++){
          md.value.$img2Url(index+1, paths[index]);
        }
      })
    }
      return {
        breadList,
        resetForm,
        ruleFormRef,
        submitForm,
        ruleForm,
        rules,
        centerDialogVisible,
        query,
        totalCount,
        tableData,
        getData,
        handleEdit,
        handleSearch,
        handleCurrentChange,
        handleDelete,
        updateimg,
        imgDel,
        imgAdd,
        md,
      };
    },
  };
  </script>
  <style lang="scss" scoped>
  .handle-box {
    margin-bottom: 20px;
  }
  
  .handle-select {
    width: 120px;
  }
  
  .handle-input {
    width: 300px;
    display: inline-block;
  }
  
  .table {
    width: 100%;
    font-size: 14px;
  }
  
  .red {
    color: #ff0000;
  }
  
  .mr10 {
    margin-right: 10px;
  }
  
  .table-td-thumb {
    display: block;
    margin: auto;
    width: 40px;
    height: 40px;
  }
  </style>
  